package com.hoshiicloud.common.validate.annotations.impl;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

import com.hoshiicloud.common.validate.annotations.URL;
import org.apache.commons.lang3.StringUtils;

import java.util.regex.Pattern;

/**
 * 网络地址验证接口实现
 *
 * @author : yangcheng
 * @date : 2019/5/16 10:10
 * @mail : maiboyc@163.com
 **/
public class URLValidatorImpl implements ConstraintValidator<URL, String> {
    @Override
    public void initialize(URL constraintAnnotation) {

    }

    @Override
    public boolean isValid(String value, ConstraintValidatorContext context) {
        if(StringUtils.isBlank(value)){
            return false;
        }
        //String regex = "[a-zA-z]+://[^\\s]* 或 ^https://([\\w-]+\\.)+[\\w-]+(/[\\w-./?%&=]*)?$";
        String regex = "^([hH][tT]{2}[pP]:/*|[hH][tT]{2}[pP][sS]:/*|[fF][tT][pP]:/*)(([A-Za-z0-9-~]+).)+([A-Za-z0-9-~\\/])+(\\?{0,1}(([A-Za-z0-9-~]+\\={0,1})([A-Za-z0-9-~]*)\\&{0,1})*)$";
        Pattern pattern = Pattern.compile(regex);
        if (pattern.matcher(value).matches()) {
            return true;
        } else {
            return false;
        }
    }
}